/* eslint-disable eqeqeq,no-undef,no-unused-vars,no-multi-spaces */

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import router from './routers';
import VueFiu from 'vue-fiu-ui';
import 'vue-fiu-ui/dist/static/css/vue-fiu-ui.css';
import './sass/app.scss';
import K from './store/config';
import './plugins/http';
import b from './plugins/Storage';

Vue.use(VueRouter);
Vue.use(VueFiu);
Vue.use(K);
Vue.use(b);

router.beforeEach((to, from, next) => {
    let user = b.storage.get(K.key.USER_DATA);
    let expiresIn = b.storage.get(K.key.EXPIRES_IN);
    let time = new Date().getTime() - (60 * 1000);
    if (expiresIn < time && expiresIn !== null) {
        updateToken();
    }
    if (user !== null) {
        user = JSON.parse(user);
        if (user.adminPanel === undefined || !user.adminPanel) {
            if (!isP(to)) {
                return next('/login');
            }
        } else {
            if (isP(to)) {
                return next('/admin/dashboard');
            } else {
                axios.post('/validate');
            }
        }
    } else {
        if (!isP(to)) {
            return next('/login');
        }
    }
    next();
});

window.__ = new Vue({
    el: '#app',
    router,
    render: h => h(App),
    data: {
        eventHub: new Vue()
    }
});

function isP (to) {
    return to.path === '/' || to.path === '/login' || to.path === '/register';
}

function updateToken () {
    axios.post('/oauth/refresh', {
        grant_type: 'refresh_token',
        refresh_token: b.storage.get(K.key.REFRESH_TOKEN),
        client_id: K.key.CLIENT_ID,
        client_secret: K.key.CLIENT_SECRET
    }).then((res) => {
        b.storage.set(K.key.ACCESS_TOKEN, res.data.access_token);
        b.storage.set(K.key.REFRESH_TOKEN, res.data.refresh_token);
        b.storage.set(K.key.EXPIRES_IN,  (new Date().getTime() + (res.data.expires_in * 1000)));
    });
}
